import Vue from "vue";
import Router from "vue-router";
import storage from "@/store/storage";
import { loading } from "@/assets/js/util";
import Full from "@/components/containers/Full";

Vue.use(Router);

//登陆界面的路径
const loginPath = window.globle.loginPath;

const globalRoutes = [
  {
    path: loginPath,
    name: "login",
    component: resolve => require(["@/views/login"], resolve),
    meta: {}
  }
];

//默认首页路径
var defaultPath = "/home";

const mainRoutes = {
  path: "/",
  name: "",
  component: Full,
  redirect: "/home",
  meta: { breadcrumb: "系统" },
  children: [
    {
      path: "/home",
      name: "首页",
      component: () => import("@/views/home"),
      meta: { breadcrumb: "首页" }
    }
  ]
};

const router = new Router({
  routes: globalRoutes.concat(mainRoutes),
  menuAdd: false //是否已经添加动态(菜单)路由
});

router.beforeEach((to, from, next) => {
  var _storage = storage;
  var token = _storage.getToken();
  var user = _storage.getUser();
  if (token) {
    //登录未过期
    if (router.options.menuAdd || isGlobalRoutes(to)) {
      if (to.name == "login") {
        //已经有toke访问login时跳转
        _storage.setLoginState(false);
        if (user) {
          next({ path: defaultPath });
        } else {
          next();
        }
      } else {
        if (_storage.getLoginState()) {
          next();
        } else {
          if (to.path == defaultPath) {
            _storage.setLoginState(true);
            next();
          } else {
            next({ path: defaultPath });
          }
        }
      }
    } else {
      addDynamicMenu();
      next({ ...to, replace: true });
    }
  } else {
    //登录已过期
    _storage.setLoginState(false);
    if (to.path == loginPath) {
      next();
    } else {
      next({ path: loginPath });
    }
  }
});

//加载动态路由地址
const addDynamicMenu = () => {
  let menus = storage.getMenus();

  menus.forEach(menu => {
    mainRoutes.children.push(backendMenusToRouters(menu));
  });
  router.options.menuAdd = true;
  router.addRoutes([
    //vue-routers2.2版本以上才支持。
    mainRoutes
  ]);
};
const backendMenusToRouters = menu => {
  if (!menu.compUrl) {
    //未配置组件url 则默认组件url=purl
    menu.compUrl = menu.url;
  }

  let route = {
    path: menu.url,
    name: menu.code,

    component: resolve => {
      require(["@/views" + menu.compUrl], resolve);
    },
    meta: {
      breadcrumb: menu.name
    },
    children: []
  };
  if (menu.children && menu.children.length !== 0 && menu.name != "") {
    menu.children.forEach(sub => {
      route.children.push(backendMenusToRouters(sub));
    });
  }
  return route;
};

//判断当前是否全局路由
function isGlobalRoutes(to) {
  for (let i in globalRoutes) {
    if (globalRoutes[i].path == to.path) {
      return true;
    }
  }
  return false;
}

router.afterEach(route => {
  window.scrollTo(0, 0);
});

export default router;
